package com.jinyijia.api.infrastructure;

import com.alibaba.fastjson.JSONObject;
import com.jinyijia.api.rest.v1.goods.dto.GoodsSearchDTO;
import com.jinyijia.api.rest.v1.goods.dto.SkuSearchDTO;
import com.jinyijia.api.rest.v1.goods.vo.GoodsSearchVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author lhw
 * @date 2018/8/15
 **/
@Service
public class GoodsManager {

    @Autowired
    @LoadBalanced
    private RestTemplate restTemplate;

    public List<GoodsSearchVO> search(String name, Long brandId, Long productId, Double minPrice, Double maxPrice, Boolean isHave, Boolean shelves) {
        JSONObject goods = restTemplate.getForObject("http://goods-service/goods?name={1}&brandId={2}&productId={3}&minPrice={4}&maxPrice={5}&shelves={6}&size=100000", JSONObject.class, name, brandId, productId, minPrice, maxPrice, shelves);
        List<GoodsSearchDTO> goodsSearchDTOS = goods.getJSONArray("content").toJavaList(GoodsSearchDTO.class);
        goodsSearchDTOS.stream().forEach(goodsSearchDTO -> {
            List<SkuSearchDTO> list = restTemplate.exchange("http://goods-service/goods/{1}/skus", HttpMethod.GET, null, new ParameterizedTypeReference<List<SkuSearchDTO>>() {
            }, goodsSearchDTO.getId()).getBody();
            goodsSearchDTO.setSkus(list);
        });
        List<GoodsSearchVO> goodsSearchVos = goodsSearchDTOS.stream().map(goodsSearchDTO -> new GoodsSearchVO(goodsSearchDTO.getId(), goodsSearchDTO.getTitle(), Objects.nonNull(goodsSearchDTO.getPicture()) ? goodsSearchDTO.getPicture().split(",")[0] : "", goodsSearchDTO.getPrice(), goodsSearchDTO.getSkus().stream().mapToLong(SkuSearchDTO::getStock).sum() > 0 ? true : false, goodsSearchDTO.getShopId(), goodsSearchDTO.getShopName())).collect(Collectors.toList());
        if (isHave) {
            return goodsSearchVos.stream().filter(GoodsSearchVO::getIsHave).collect(Collectors.toList());
        }
        return goodsSearchVos;
    }
}
